<template>
<div class="policy-form">
    <div class="form-area">
        <el-form ref="form" :model="form" label-width="100px" v-loading="listLoading">
            <el-form-item label="标识符">
                <el-input v-model="form.id" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="政策标题">
                <el-input v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item label="发文字号">
                <el-input v-model="form.number"></el-input>
            </el-form-item>
            <el-form-item label="发布机构">
                <el-select v-model="form.publishOrganList"  value-key="id"  :multiple="true" filterable placeholder="请选择">
                    <el-option v-for="(organ,index) in organList" :key="index" :label="organ.name" :value="organ.name"></el-option>
                </el-select>

                <el-button class="jigou-button-new" size="small" @click="dialog_jigou_addClick">机构不存在?点此添加</el-button>

            </el-form-item>
            <el-form-item label="发布日期">
                <el-date-picker v-model="form.publishDate" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
            <el-form-item label="获取网址">
                <el-input v-model="form.url"></el-input>
            </el-form-item>
            <el-form-item label="主题分类">
                <el-input v-model="form.category"></el-input>
            </el-form-item>
            <el-form-item label="执行截止日期">
                <el-date-picker v-model="form.endDate" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
            <el-form-item label="效力级别">
                <el-select v-model="form.validity" :value="form.validity" placeholder="请选择" style="width: 200px">
                  <el-option :label="level.label" :value="level.value" v-for="(level,idx) in levelList" :key="idx"></el-option>
                </el-select>
            </el-form-item>

            <!--<el-form-item label="有效性">
                <el-input v-model="form.validity"></el-input>
            </el-form-item>-->

            <el-form-item label="文种类型">
                <el-select v-model="form.type" :value="form.type" placeholder="请选择" style="width: 200px">
                  <el-option :label="level.label" :value="level.value" v-for="(level,idx) in typeList" :key="idx"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="地域">
                <el-input v-model="form.region"></el-input>
            </el-form-item>
            <el-form-item label="特殊地域">
                <el-input v-model="form.specialRegion"></el-input>
            </el-form-item>

            <el-form-item label="关键词">
                <el-tag :key="tag" v-for="tag in form.keyword" closable :disable-transitions="false" @close="tag_handleClose(tag)">{{tag}}</el-tag>

                <el-input class="tag-input-new" v-if="tag_inputVisible" v-model="tag_inputValue" ref="saveTagInput" size="small"  @keyup.enter.native="tag_handleInputConfirm" @blur="tag_handleInputConfirm"></el-input>
                <el-button v-else class="tag-button-new" size="small" @click="tag_showInput">+ 新增</el-button>
            </el-form-item>

            <el-form-item label="全文">
                <!--<el-input type="textarea" v-model="form.content" :rows="8"></el-input>-->
                <tinymce v-model="form.content" :height="300" menubar="" :toolbar="tinymce_toolbar"/>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="onSubmit">提交</el-button>
                <el-button type="primary" @click="mark_done" style="margin-left:80px;">已完成加工</el-button>
                <el-button type="primary" @click="mark_no">不加工</el-button>
            </el-form-item>
        </el-form>

    </div>


      <el-dialog title="添加机构" :visible.sync="dialog_jigou_FormVisible" width="30%">
        <el-form :model="dialog_jigou_form" size="small">
          <el-form-item label="机构名称" :label-width="dialog_jigou_formLabelWidth">
            <el-input v-model="dialog_jigou_form.name" auto-complete="off" style="width: 200px"></el-input>
          </el-form-item>

          <el-form-item label="简称" :label-width="dialog_jigou_formLabelWidth">
              <div v-for="(val,idx) in dialog_jigou_form.shortNameList" class="lineItem">
                  <el-input v-model="val.name" auto-complete="off" style="width: 200px"></el-input>
                  <el-button type="text" @click="dialog_jigou_shortname_del(idx)">删除</el-button>
              </div>
              <el-button @click="dialog_jigou_shortname_add()" type="primary" plain size="small">新增</el-button>
          </el-form-item>

          <el-form-item label="效力级别" :label-width="dialog_jigou_formLabelWidth">
            <el-select v-model="dialog_jigou_form.level" :value="dialog_jigou_form.level" placeholder="请选择" style="width: 200px">
              <el-option :label="level.label" :value="level.value" v-for="(level,idx) in levelList" :key="idx"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog_jigou_FormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialog_jigou_confirmClick">确 定</el-button>
        </div>
      </el-dialog>


</div>
</template>

<script>
import { getPolicyById, getAllOrgan, submit } from "@/api/policy-edit";
import { setState } from "@/api/mark-policy";

import { editPublish } from '@/api/publish-data'

import Tinymce from '@/components/Tinymce'

export default {
    name: 'PagePermission',
    components: { Tinymce },
    data() {
        return {
            tinymce_toolbar : ['bold | alignleft aligncenter alignright | code'],

            levelList: [
              {label: '法律', value: '法律'},
              {label: '行政法规', value: '行政法规'},
              {label: '部门规章', value: '部门规章'},
              {label: '地方性法规', value: '地方性法规'},
              {label: '地方政府规章', value: '地方政府规章'},
              {label: '地方性规范文件', value: '地方性规范文件'},
            ],

            typeList:[
              {label: '通知', value: '通知'},
              {label: '意见', value: '意见'},
              {label: '办法', value: '办法'},
              {label: '公告', value: '公告'},
              {label: '决定', value: '决定'},
              {label: '方案', value: '方案'},
              {label: '规定', value: '规定'},
              {label: '计划', value: '计划'},
              {label: '条例', value: '条例'},
              {label: '细则', value: '细则'},
              {label: '令', value: '令'},
              {label: '函', value: '函'},
              {label: '其他', value: '其他'},
            ],

              // 关键词tag
            tag_inputVisible: false,
            tag_inputValue: '',

            organList: [],          // 所有的发布机构  [{id:1, name:'xxx', level:'行政法规'}]

              // 政策信息
            policyId: '',
            listLoading: false,
            form: {
                id: '',
                title: '',
                number: '',
                publishDate: '',
                url: '',
                category: '',
                endDate: '',
                //level: '',
                validity: '',       // 效力级别
                content: '',
                fileUrl: '',
                specialRegion: '',      // 特殊地域
                type: '',               // 文种类型

                publishOrganList: [],           // [{id:1, name:'xxx'}]
                keyword: [],
            },

            //////  弹窗-新增机构
            dialog_jigou_FormVisible: false,
            dialog_jigou_formLabelWidth: '120px',
            dialog_jigou_form: {
              id: '',
              name: '',
              level: '',
              shortNameList: [],
            },
            levelList: [
              {label: '法律', value: '法律'},
              {label: '行政法规', value: '行政法规'},
              {label: '部门规章', value: '部门规章'},
              {label: '地方性法规', value: '地方性法规'},
              {label: '地方政府规章', value: '地方政府规章'},
              {label: '地方性规范文件', value: '地方性规范文件'},
            ]

        }
    },
    computed: {},
    created() {
        console.log('[created]');
        this.getAllOrgan();

        if (this.$route.query.id) {
            this.policyId = this.$route.query.id;
            this.getPolicy();
        }
    },
    methods: {

        /*
            {
              "title": "标题",
              "number": "发文字号",
              "publishOrgan": "上海市规划和国土资源管理局",
              "publishDateString": "2020-01-01",
              "publishYear": "2020年",
              "url": "http://127.0.0.1",
              "category": "主题分类",
              "endDateString": "2020-12-12",
              // 有效性
              "validity": "效力级别",
              "keyword": "关键词1;关键词2",
              "content": "政策内容",
              "specialRegion": "特殊地域"
              "type": "文种类型",   值: 通知、意见、办法、公告、决定、方案、规定、计划、条例、细则、令、函、其他

              "region": "全国",
              "adjunct": "附件",
              "wordFreamString": "科技创新要素>产业发展用地政策"
            }
        */
        onSubmit() {

            this.listLoading = true;
            // 处理数据
            var data = {};
            if(0){
                this.form.keyword=[];
                this.form.publishOrganList=['国务院'];
                ['deleteDate','createDate','endDate','updateDate'].forEach((item) => {
                    delete(this.form[ item ]);
                });
                data = this.form;
            }else{

                console.log( this.form['publishOrganList'] );
                data = {
                    id              : this.form['id'],
                    title           : this.form['title'],
                    number          : this.form['number'],
                    url             : this.form['url'],
                    category        : this.form['category'],
                    validity        : this.form['validity'],      // "有效性",
                    specialRegion   : this.form['specialRegion'],      // "特殊地域",
                    type            : this.form['type'],      // "文种类型",

                    publishDateString: this.form['publishDate'],     // "2020-01-01",       // 要转换
                    endDateString   : this.form['endDate'],     // "2020-01-01",            // 要转换
                    publishYear     : new Date(this.form['publishDate']).getFullYear() + '年',      // "2020年",

                    publishOrgan    : this.form['publishOrganList'].join(';'),                        // 要转换
                    keyword         : this.form['keyword'].join(';'),      // "关键词1;关键词2",

                    content         : this.form['content'],

                    region          : this.form['region'],      // "全国",
                    adjunct         : this.form['adjunct'],      // "附件",
                    wordFreamString : this.form['wordFreamString'],      // "科技创新要素>产业发展用地政策"
                }

                /*let data2 = {
                    "title"             : "标题2",
                    //"number"            : "发文字号",
                    "publishOrgan"      : "上海市规划和国土资源管理局",
                    "publishDateString" : "2020-01-01",
                    //"publishYear"       : "2020年",
                    "url"               : "http://127.0.0.1/?t=1",
                    "category"          : "主题分类",
                    "endDateString"     : "2020-12-12",
                    // 效力级别
                    "validity"          : "有效性",
                    "keyword"           : "关键词1;关键词2",
                    "content"           : "政策内容",

                    "region"            : "全国",
                    "adjunct"           : "附件",
                    "wordFreamString"   : "科技创新要素>产业发展用地政策"
                }*/
            }

            //console.log(data);this.listLoading = false;return;

            /*
            {"id":"", "title":"aaaaaa", "number":"aaaaaa", "publishOrganList":["国务院"], "publishDate":"2020-09-02T16:00:00.000Z", "url":"", "category":"aaaaaa", "level":"",
              "validity":"现行有效", "keyword":"","content":"<p>aaaaaaaaaaaaaaaaaa</p>", "fileUrl":""}
            */

              // 通过url字段, 来做识别的
            submit(data).then(res => {
                this.listLoading = false;
                this.$message({ message: "修改成功", type: "success" });
            });
        },

        getPolicy() {
            if (this.policyId) {
                this.listLoading = true;

                getPolicyById({id: this.policyId}).then(res => {
                    this.listLoading = false;
                      // 预处理数据
                    res.result.keyword = res.result.keyword ? res.result.keyword.split(';') : [];
                    res.result.publishOrganList = res.result.publishOrgan ? res.result.publishOrgan.split(';') : [];
                    //res.result.publishOrganList = res.result.publishOrganList;

                    this.form = res.result;

                });
            }

        },

          // 获取所有的发布机构
        getAllOrgan() {
            let param = { pageSize: 1000, pageNum: 1, key: '', };
            getAllOrgan(param).then(res => {
                this.organList = res.result.list;
            })
        },


          /********** tag相关 **********/
        tag_handleClose(tag) {
            this.form.keyword.splice(this.form.keyword.indexOf(tag), 1);
        },
        tag_showInput() {
            this.tag_inputVisible = true;
            this.$nextTick(_ => {
              this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        tag_handleInputConfirm() {
            let inputValue = this.tag_inputValue;
            if (inputValue) {
                this.form.keyword.push(inputValue);
            }
            this.tag_inputVisible = false;
            this.tag_inputValue = '';
        },


          // 已完成加工
        mark_done() {
            this.$confirm("确认是否已提交加工信息?", {type: "warning"}).then(() => {
                if (this.policyId) {
                    let param={
                        id : this.policyId,
                        state: 1,
                    }
                    setState(param).then(res => {
                        this.$message({ message: '设置成功！', type: 'success' });
                    });
                }
            }).catch(() => {})
        },
          // 不加工
        mark_no() {
            this.$confirm("设置为“不加工”状态，则该政策不会在前台显示。确定设置?", {type: "warning"}).then(() => {
                let param={
                    id : this.policyId,
                    state: 2,
                }
                setState(param).then(res => {
                    this.$message({ message: '设置成功！', type: 'success' });
                });
            }).catch(() => {})
        },




          /**************************************** 弹窗-新增机构 begin ****************************************/


          dialog_jigou_addClick(){
            this.dialog_jigou_form.id = 0;
            this.dialog_jigou_form.name = '';
            this.dialog_jigou_form.level = '行政法规';
            this.dialog_jigou_form.shortNameList = [];
            this.dialog_jigou_FormVisible = true;
          },

          dialog_jigou_confirmClick() {
              if( !this.dialog_jigou_form.name ){  this.$message({ message: "请输入机构名称", type: "error"}); return; }
              if( !this.dialog_jigou_form.level ){  this.$message({ message: "请选择效力级别", type: "error"}); return; }

              this.dialog_jigou_form.shortNameList = this.dialog_jigou_form.shortNameList.filter(function(item) { return item.name.trim() != ''; });

              this.listLoading = true;
              let param = this.dialog_jigou_form;
              if( !param.id ){
                    delete param.id;
              }
              editPublish(param).then(res => {
                    this.$message({ message: '机构添加成功！', type: 'success' });
                    this.getAllOrgan();
                    this.listLoading = false;
                    this.dialog_jigou_FormVisible = false
              }).catch(error => {
                    this.listLoading = false;
              })
          },
          dialog_jigou_shortname_add(){
            this.dialog_jigou_form.shortNameList.push( {name:''} );
          },
          dialog_jigou_shortname_del( idx ){
            this.dialog_jigou_form.shortNameList.splice( idx, 1 );
          },

          /**************************************** 弹窗-新增机构 end ****************************************/



    }
}
</script>
<style lang="less" scoped>
.policy-form {
    padding-top: 24px;

    .form-area {
        width: 70%;
        margin: auto;

        .el-input, .el-date-picker, .el-select {
            width: 400px;
        }

        .el-tag { margin-right: 10px; }
        .tag-button-new { height: 32px; line-height: 30px; padding-top: 0; padding-bottom: 0; }
        .tag-input-new { width: 90px; vertical-align: bottom; }

        .jigou-button-new{margin-left:20px;}
    }
}
</style>
<style lang="less">
.tinymce-container .editor-custom-btn-container{
    display:none!important;
}
</style>